import { provide, inject, ref, unref, hasInjectionContext, watch } from 'vue'
import { useRoute } from 'vue-router'
import { message as Message } from 'ant-design-vue'
import { debounce } from 'lodash-es'
import { nanoid } from 'nanoid'
import { getFileInfoList, getFileInfo, getPermission } from '@/api/db.js'
/**
 * Symbol
 */
export const columnsSymbol = Symbol('columns')
export const dataSourceSymbol = Symbol('dataSource')
export const querySymbol = Symbol('query')
export const lineheightSymbol = Symbol('lineheight')
export const loadingSymbol = Symbol('loading')
export const dataSourceRowNewSymbol = Symbol('dataSourceRowNew')
export const groupIdSymbol = Symbol('groupId')
export const categoryIdSymbol = Symbol('categoryId')
export const treeSelectedInfoSymbol = Symbol('treeSelectedInfo')
export const rowSelectionSymbol = Symbol('rowSelection')
export const rowSelectionActiveSymbol = Symbol('rowSelectionActive')
export const sortCreatetimeTypeSymbol = Symbol('sortCreatetimeType')
export const publishCountSymbol = Symbol('publishCount')
export const uploadLocalFileListSymbol = Symbol('uploadLocalFileList')
export const importFileListSymbol = Symbol('importFileList')
export const createFolderDisabledSymbol = Symbol('createFolderDisabled')
export const uploadLocalRefSymbol = Symbol('uploadLocalRef')
export const publishDrawerContentKeySymbol = Symbol('publishDrawerContentKey')
export const lockForInUseSymbol = Symbol('lockForInUse')
export const downloadBarVisibleSymbol = Symbol('downloadBarVisible')
export const transferBarVisibleSymbol = Symbol('transferBarVisible')
export const tagBarVisibleSymbol = Symbol('tagBarVisibleSymbol')
export const permissionSymbol = Symbol('permission')
export const staticPermissionSymbol = Symbol('staticPermission')
export const dbTypeSymbol = Symbol('dbType')

/**
 * 注册
 */
export function useProvideContextRegistry({
  groupId,
  categoryId,
  treeSelectedInfo,
  createFolderDisabled = false,
  useSearchQueryDataname = false,
  staticPermission,
}) {
  let route = useRoute()
  let columns = ref([])
  let dataSource = ref([])
  let query = ref({})
  if (useSearchQueryDataname) {
    query.value = { keyWord: route.query.dataname }
  }
  let lineheight = ref()
  let loading = ref(false)
  let selectedRowKeys = ref([])
  let selectedRowInfos = ref([])

  let rowSelection = {
    selectedRowKeys,
    selectedRowInfos,
    onChange: (keys, infos) => {
      selectedRowKeys.value = keys
      selectedRowInfos.value = infos
    },
  }
  let rowSelectionActive = ref(false)
  let sortCreatetimeType = ref()
  let publishCount = ref(0)
  let uploadLocalFileList = ref([])
  let importFileList = ref([])
  let uploadLocalRef = ref()
  let publishDrawerContentKey = ref(Date.now())
  let lockForInUseRef = ref(null)
  let downloadBarVisibleRef = ref(false)
  let transferBarVisibleRef = ref(false)
  let tagBarVisibleRef = ref(false)
  let permission = ref({})

  provide(columnsSymbol, columns)
  provide(dataSourceSymbol, dataSource)
  provide(querySymbol, query)
  provide(lineheightSymbol, lineheight)
  provide(loadingSymbol, loading)
  provide(groupIdSymbol, groupId)
  provide(categoryIdSymbol, categoryId)
  provide(rowSelectionSymbol, rowSelection)
  provide(rowSelectionActiveSymbol, rowSelectionActive)
  provide(sortCreatetimeTypeSymbol, sortCreatetimeType)
  provide(publishCountSymbol, publishCount)
  provide(uploadLocalFileListSymbol, uploadLocalFileList)
  provide(importFileListSymbol, importFileList)
  provide(createFolderDisabledSymbol, createFolderDisabled)
  if (treeSelectedInfo) {
    provide(treeSelectedInfoSymbol, treeSelectedInfo)
    //监听点击树变化
    watch(treeSelectedInfo, () => {
      query.value.keyWord = ''
    })
  }
  provide(uploadLocalRefSymbol, uploadLocalRef)
  provide(publishDrawerContentKeySymbol, publishDrawerContentKey)
  provide(lockForInUseSymbol, lockForInUseRef)
  provide(downloadBarVisibleSymbol, downloadBarVisibleRef)
  provide(transferBarVisibleSymbol, transferBarVisibleRef)
  provide(tagBarVisibleSymbol, tagBarVisibleRef)
  provide(permissionSymbol, permission)
  provide(staticPermissionSymbol, staticPermission)
}

/**
 * 获取值
 */
export function useColumns() {
  return inject(columnsSymbol)
}
export function useDataSource() {
  return inject(dataSourceSymbol)
}
export function useQuery() {
  return inject(querySymbol)
}
export function useLineheight() {
  return inject(lineheightSymbol)
}
export function useLoading() {
  return inject(loadingSymbol)
}
export function useGroupId() {
  return inject(groupIdSymbol)
}
export function useCategoryId() {
  return inject(categoryIdSymbol)
}
export function useRowSelection() {
  return inject(rowSelectionSymbol)
}
export function useRowSelectionActive() {
  return inject(rowSelectionActiveSymbol)
}
export function useSortCreatetimeType() {
  return inject(sortCreatetimeTypeSymbol)
}
export function usePublishCount() {
  return inject(publishCountSymbol)
}
export function useUploadLocalFileList() {
  return inject(uploadLocalFileListSymbol)
}
export function useImportFileList() {
  return inject(importFileListSymbol)
}
export function useTreeSelectedInfo() {
  return inject(treeSelectedInfoSymbol)
}
export function useCreateFolderDisabled() {
  return inject(createFolderDisabledSymbol)
}
export function useUploadLocalRef() {
  return inject(uploadLocalRefSymbol)
}
export function usePublishDrawerContentKey() {
  return inject(publishDrawerContentKeySymbol)
}
export function useLockForInUse() {
  return inject(lockForInUseSymbol)
}
export function useDownloadBarVisible() {
  return inject(downloadBarVisibleSymbol)
}
export function useTransferBarVisible() {
  return inject(transferBarVisibleSymbol)
}
export function useTagBarVisible() {
  return inject(tagBarVisibleSymbol)
}
export function usePermission() {
  return inject(permissionSymbol)
}
export function useStaticPermission() {
  return inject(staticPermissionSymbol)
}
export function useDbType() {
  return inject(dbTypeSymbol, false)
}

/**
 * 管理工具
 */
let otherQueryStringPrev = ''
export function useDataSourceManager() {
  let dataSource = useDataSource()
  let query = useQuery()
  let loading = useLoading()
  let groupId = useGroupId()
  let categoryId = useCategoryId()
  let sortCreatetimeType = useSortCreatetimeType()
  let permission = usePermission()
  let staticPermission = useStaticPermission()
  let dbType = useDbType()
  let update = debounce(async () => {
    if (!groupId.value) {
      return
    }
    loading.value = true
    //判断otherQueryString是否有变化来决定current是否需要初始化到第一页
    let { current, pageSize, ...otherQuery } = query.value
    let otherQueryString = JSON.stringify(otherQuery)
    if (
      otherQueryString !== otherQueryStringPrev &&
      otherQueryStringPrev !== ''
    ) {
      current = 1
    }
    otherQueryStringPrev = otherQueryString
    let groupIdCurrent = groupId.value
    try {
      //获取权限
      let resultPermission
      if (staticPermission) {
        resultPermission = { data: staticPermission }
      } else {
        resultPermission = await getPermission({ id: categoryId.value }, dbType)
      }
      permission.value = resultPermission.data || {}
      // {
      //   view: true,
      //   move: true,
      //   download: true,
      //   import: true,
      //   edit: true,
      //   upload: true,
      //   delete: true,
      //   export: true,
      // }
      //resultPermission.data || {}
      //没有view项，默认开启
      permission.value.view = true

      //获取数据
      let params = {
        pageIndex: current,
        pageSize,
        keyWord: otherQuery.keyWord,
        tags: otherQuery.tags,
        parentId: groupIdCurrent,
        saveStatus: 'success',
      }
      // //含有排序条件
      // if (sortCreatetimeType.value?.order) {
      //   params[sortCreatetimeType.value.field] =
      //     sortCreatetimeType.value.order.replace(/end$/, '')
      // }
      // console.log(otherQuery, sortCreatetimeType.value)
      //隐射新入参
      params = {
        parentId: params.parentId,
        pageNum: params.pageIndex,
        pageSize: params.pageSize,
        keyword: params.keyWord,
        tagIds: params.tags,
        fileType: params.fileType, //??
        //// 差文件名称
        createdTimeSort: params.createdTimeSort,
        versionSort: params.versionSort,
        fileSizeSort: params.fileSizeSort,
        dataStatus: params.dataStatus,
      }

      /**
       * 排序参数
       */
      if (sortCreatetimeType.value?.order) {
        //文件版本排序
        if (sortCreatetimeType.value?.field === 'version') {
          if (sortCreatetimeType.value?.order === 'ascend') {
            params.versionSort = 0
          }
          if (sortCreatetimeType.value?.order === 'descend') {
            params.versionSort = 1
          }
        }
        //创建时间排序
        if (sortCreatetimeType.value?.field === 'gmtCreate') {
          if (sortCreatetimeType.value?.order === 'ascend') {
            params.createdTimeSort = 0
          }
          if (sortCreatetimeType.value?.order === 'descend') {
            params.createdTimeSort = 1
          }
        }
        //文件大小排序
        if (sortCreatetimeType.value?.field === 'fileSizeShow') {
          if (sortCreatetimeType.value?.order === 'ascend') {
            params.fileSizeSort = 0
          }
          if (sortCreatetimeType.value?.order === 'descend') {
            params.fileSizeSort = 1
          }
        }
        //文件名排序
        if (sortCreatetimeType.value?.field === 'dataName') {
          if (sortCreatetimeType.value?.order === 'ascend') {
            params.fileNameSort = 0
          }
          if (sortCreatetimeType.value?.order === 'descend') {
            params.fileNameSort = 1
          }
        }
        //文件类型排序
        if (sortCreatetimeType.value?.field === 'fileType') {
          if (sortCreatetimeType.value?.order === 'ascend') {
            params.fileTypeSort = 0
          }
          if (sortCreatetimeType.value?.order === 'descend') {
            params.fileTypeSort = 1
          }
        }
        //更新时间排序
        if (sortCreatetimeType.value?.field === 'updatedTime') {
          if (sortCreatetimeType.value?.order === 'ascend') {
            params.updatedTime = 0
          }
          if (sortCreatetimeType.value?.order === 'descend') {
            params.updatedTime = 1
          }
        }
      }

      /**
       * 过滤参数？？？？
       */

      if (otherQuery.filters) {
        if (otherQuery.filters.fileType instanceof Array) {
          if (otherQuery.filters.fileType.length > 0) {
            params.fileType = otherQuery.filters.fileType[0]
          }
        }
        if (otherQuery.filters.dataStatus instanceof Array) {
          if (otherQuery.filters.dataStatus.includes('occupy')) {
            params.dataStatus = 2
          }
          if (otherQuery.filters.dataStatus.includes('publish')) {
            params.dataStatus = 1
          }
        }
      }
      //   {
      //     "total": 4,
      //     "filters": {
      //         "fileType": [
      //             "1"
      //         ],
      //         "dataStatus": [
      //             "occupy"
      //         ]
      //     }
      // }
      // console.log(params)
      let result = (await getFileInfo(params, dbType)) || {}
      //点的太快多次请求，只获取最后匹配到的groupId那次
      if (groupIdCurrent !== groupId.value) {
        return
      }

      query.value.current = result?.data?.pageNum || current
      query.value.pageSize = result?.data?.pageSize || pageSize
      query.value.total = result?.data?.total || 0
      dataSource.value = (result?.data?.records || [])
        .map(item => ({
          ...item,
          key: item.dataId,
        }))
        //隐射新出参
        .map(item => {
          let {
            id,
            fileId,
            fileType,
            fileName,
            fileNote,
            fileVersion,
            parentId,
            dataType,
            dataStatus,
            saveStatus,
            fileSize,
            fileSizeShow,
            updatedTime,
            createdTime,
            fileCode,
            isFavorite,
          } = item
          return {
            id,
            key: id,
            dataId: id,
            fileId,
            dataName: fileName,
            dataType: dataType === 0 ? 'folder' : 'file',
            fileType: fileType,
            version: fileVersion,
            gmtCreate: createdTime,
            // gmtBatchUpload: updatedTime,
            dataStatus, //占存状态相关
            note: fileNote,
            saveStatus, //是否保存成功
            //新增
            parentId,
            fileSize,
            fileSizeShow,
            fileCode,
            updatedTime,
            isFavorite,
          }
        })
      loading.value = false
    } catch (e) {
      console.log(e)
      dataSource.value = []
      Message.error('列表加载失败')
      loading.value = false
    }
  }, 300)
  function createEmpty() {
    let id = nanoid()
    dataSource.value = [
      // {
      //   id: id,
      //   key: id,
      //   dataName: '',
      //   dataType: 'folder',
      //   dataId: '-',
      //   note: '',
      //   gmtCreate: '-',
      //   dataStatus: '-',
      //   editing: true,
      //   loading: false,
      //   new: true,
      // },

      {
        id,
        key: id,
        dataId: '-',
        dataName: '',
        dataType: 'folder',
        // fileType: fileType,
        // version: fileVersion,
        gmtCreate: '-',
        // gmtBatchUpload: updatedTime,
        dataStatu: '-', //??
        note: '',
        // saveStatus: saveStatus, //??
        //新增
        // parentId,
        // fileSize,
        // fileSizeShow,
        // fileCode,
        updatedTime: '-',
        editing: true,
        loading: false,
        new: true,
      },
      ...dataSource.value,
    ]
  }
  function removeEmpty() {
    dataSource.value = dataSource.value.filter(({ new: n }) => !n)
  }

  return { update, createEmpty, removeEmpty }
}
export function useQueryManager() {
  let query = useQuery()
  return {
    set(newQuery) {
      query.value = unref(newQuery)
    },
    assign(newQuery) {
      query.value = Object.assign({}, query.value, newQuery)
    },
  }
}

// /**
//  * 数据
//  */
// let ds = () =>
//   Array(100)
//     .fill(1)
//     .map((i, index) => ({
//       id: index + '',
//       key: index,
//       name: '胡1231彦斌xx213xxxxxxasdas12',
//       filetype: Math.random() > 0.5 ? 'folder' : '',
//       encoding: '西湖区湖底公园1号',
//       createtime: '2024-10-22 14:07:47',
//       remark: 'asdxxxxxxxxxxxxxxxxxxxxxxxxxxxxx水水水水水xx是',
//       status: Math.random() > 0.5 ? 0 : 1,
//       editing: false,
//       loading: false,
//     }))
